const puppeteer = require('puppeteer');

exports.login = function () {
  return new Promise(resolve => {
    puppeteer.launch({ headless: false }).then(async browser => {
      const page = await browser.newPage();
      await page.goto('http://172.19.196.155:2902/trueOA/portalHome_portal.do', { waitUntil: 'domcontentloaded' });
      await page.type('#username', 'zhzhzx');
      await page.type('#password', 'bgs866_');
      await Promise.all([
        page.waitForNavigation(),
        page.click('.btn_sub')
      ]);
      page.on('dialog', async dialog => { await dialog.dismiss(); });

      const pages = await browser.pages();
      const newPage = pages[pages.length - 1];
      var jsessionid = newPage.url().split('jsessionid=')[1];
      var cookieMap = {
        trueOA: jsessionid
      };
  
      var workFlowPage = await browser.newPage();
      workFlowPage.on('dialog', async dialog => { await dialog.dismiss(); });
      await workFlowPage.goto('http://172.19.196.155:2902/trueWorkFlow/table_openReceiveForm.do?receiveId=A8A0D9E9-0CAB-4C52-8EC6-5FBE065D5E29&jrdb=true&status=0', { waitUntil: 'domcontentloaded' })
      
      var cookies = await workFlowPage.cookies();
      var jsessionid2 = cookies.find(n => n.name == 'JSESSIONID').value;
      cookieMap.trueWorkFlow = jsessionid2;
      await browser.close();
      resolve(jsessionid2);
    });
  });
}

